package com.yc.d0304;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.*;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

     public static Map<String, Long> onlineUsers = new HashMap<>();

    public OnlineListener() {
    }



    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        sbe.getName(); //添加到会话中的属性名
        sbe.getValue();//添加到会话中的属性值
        if (sbe.getName().equals("loginedUser")){
            onlineUsers.put((String) sbe.getValue(),
                    (Long)sbe.getSession().getAttribute("loginedTime"));
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        if (sbe.getName().equals("loginedUser")){
            onlineUsers.remove((String) sbe.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        if (sbe.getName().equals("loginedUser")){
            String oldName = (String) sbe.getValue();
            String newName=(String) sbe.getSession().getAttribute("loginUser");

            onlineUsers.remove(oldName);
            onlineUsers.put((String) sbe.getValue(),
                    (Long)sbe.getSession().getAttribute("loginedTime"));
        }
    }
}
